<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>M3U8视频播放</title>
    <script src="./hls.js"></script>
  </head>
  <body>
    <video id="video" controls autoplay muted></video>
    <script>
      var hls
      window.addEventListener('message', function (event) {
        console.log('收到视频消息', event.data.message)
        if (event.data.message == 'close') {
          this.stopVideoStream()
        } else {
          const video = document.getElementById('video')
          const videoSrc = event.data.message
          hls = new Hls()
          this.playVideoStream(video, videoSrc)
        }
      })

      function playVideoStream(video, videoSrc) {
        if (Hls.isSupported()) {
          window.hlsInstance = hls
          hls.loadSource(videoSrc)
          hls.attachMedia(video)
          hls.on(Hls.Events.MANIFEST_PARSED, function () {
            video.play()
          })
        } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
          // For Safari or native HLS support
          video.src = videoSrc
          video.play()
        } else {
          console.log('浏览器不支持HLS')
        }
      }

      function stopVideoStream() {
        const video = document.getElementById('video')
        const hls = window.hlsInstance // 你需要确保这个 hlsInstance 在全局或闭包中可访问

        if (hls) {
          hls.destroy() // 销毁 Hls 实例
          //hls = null // 清除引用
          video.src = '' // 清空视频源
          video.pause() // 停止视频播放
          // video.load() // 重新加载视频（可选，但有助于清除缓存）
        } else {
          video.pause() // 如果 Hls 实例不存在，直接停止视频播放
          // video.load() // 重新加载视频（可选）
        }
      }
    </script>
  </body>

  <style>
    body {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    #video {
      width: 355px;
      height: 210px;
    }
  </style>
</html>
